/**
 * 登录模块，提供登录相关业务功能
 * 
 * @Date: 2015-6-16
 * @author: Jackson wang
 * @version: 1.0
 * @since: 1.0
 */
define(["jquery", "msgServ", "ajaxServ","datagridServ","treegridServ","bizProto","btnServ"],
		function($, msgServ, ajaxServ,datagridServ,treegridServ,bizProto,btnServ) {

			'use strict';

			var _bizProto,righttreeExpanded=false,_buttonConfig,
				$rolePermissionPermission,$rolePermissionPermissionGrid,$rolePermissionRole,$rolePermissionRoleGrid,
				$edit_window ,
				permissionQueryUrl = '/permission/query/getTreeList.action',baseRightQueryUrl,
				roleQueryUrl = '/role/query/getListDomain.action',baseLeftQueryUrl,
				roleEditUrl = '/role/editPage.action',baseLeftEditUrl,
				rolePermissionSaveUrl = '/rolePermission/save.action',baseSaveUrl,
				permissionByRoleQueryUrl = '/rolePermission/getPermissionByRole.action',baseRightByLeftIdQueryUrl,
				roleDelUrl = '/rolePermission/del.action', baseLeftDelUrl,
				
				//列表页面dom id
				rootid ='panel-permissionAssign',
				
				//当前角色具有的权限
				currentRows,
				
				//当前角色选中行
				currentJobRow,
				
				//新增权限资源
				insertedRows,
				
				//删除的权限资源
				deletedRows;

			var private_method = {
				
				//初始化方法
				init : function(doc) {
					if (window.console) {
					console.info('permissionAssign modules gets ready and been loaded.');
					}
					_bizProto = new bizProto({doc:doc,rootId:'panel-permissionAssign',panelSelector:'div.well'});
					_bizProto.gridHeight -= 15;
					
					_buttonConfig={
						"新增":private_method.add,
					    "编辑":private_method.edit,
						 "删除":private_method.del,
						 "保存设置":private_method.saveRolesPermission
						 							
					}
					private_method.initPath();
					private_method.initElement(_bizProto.pageDoc)
				},
				
				//初始化路径
				initPath:function(){
					baseRightQueryUrl = _bizProto.rootPath + permissionQueryUrl;
					baseLeftQueryUrl = _bizProto.rootPath + roleQueryUrl;
					baseLeftEditUrl = _bizProto.rootPath +roleEditUrl;
					baseSaveUrl = _bizProto.rootPath + rolePermissionSaveUrl;
					baseRightByLeftIdQueryUrl = _bizProto.rootPath + permissionByRoleQueryUrl;
					baseLeftDelUrl = _bizProto.rootPath + roleDelUrl;
				},
				//初始化页面元素
				initElement:function(doc){
					
				public_method.destory();
				
				$edit_window = $('#roleEdit-win');
				$rolePermissionRole = $(doc).find("#dg-rolePermission-role");
				$rolePermissionRoleGrid = $rolePermissionRole.datagrid({
					url : baseLeftQueryUrl,					
					height : _bizProto.gridHeight,				
					//onClickRow:function(rowIndex, rowData){private_method.getPermission(rowIndex, rowData)}
					onClickRow : function(rowIndex, rowData){
						public_method.destory();
						private_method.getPermission(rowIndex, rowData)}
				});

				$rolePermissionPermission = $(doc).find("#dg-rolePermission-permission");
				$rolePermissionPermissionGrid= $rolePermissionPermission.treegrid({
					width : 'auto',
					height : _bizProto.gridHeight,
					url : baseRightQueryUrl,					
					onLoadSuccess:function(row,data){
							if(data && currentRows){
								private_method.refreshPermissionByExpandNode(data);
							}
						},
						onSelect:function(row){
							//选中角色判断
							if(currentJobRow){
								
								if(!insertedRows){
									insertedRows = {}
								} 
								
								//从已删除中清除数据
								if(deletedRows && deletedRows[row.id]){
									delete deletedRows[row.id]
								}else{
									//当前权限中无选中权限
									if(!currentRows || !currentRows[row.id]){
										//在呆增加数据中添加此条记录
										insertedRows[row.id]={
											permissionid:row.id,
											roleid:currentJobRow.id
										}
									}
								}
							}
						},
						onUnselect:function(row){
							//选中角色判断
							if(currentJobRow){
								
								if(insertedRows && insertedRows[row.id]){
									delete insertedRows[row.id]
								}else{
									if(!deletedRows){
										deletedRows = {}
									}
									if(currentRows && currentRows[row.id]){
										deletedRows[row.id] = currentRows[row.id]
									}
									
								}
								
							}
						}					
					}				
				);

				
				
				$('#tb-rolePermission-role a.easyui-linkbutton').unbind('click');
				$('#tb-rolePermission-role a.easyui-linkbutton').bind('click',private_method.function_btn_listenner)
				
				$.messager.progress('close');
				},
				getPermission:function (rowIndex, rowData){
					
					currentJobRow = rowData;
					$rolePermissionPermission.treegrid("unselectAll");
					var _p = {
					 	type:'post',
					 	data:{roleid:rowData.id},
					 	url:baseRightByLeftIdQueryUrl,
					 	success:function(data){
					 		if(!data || data.total <=0){
					 			msgServ.Msgslide('当前角色尚未配置任何权限资源');
					 		}
					 		
					 		currentRows = private_method.getIdJson(data);
					 		private_method.refreshPermissionByClickRole(data);
					 		
					 		
					 	},
					 	failure:function(){
					 		msgServ.Msgslide('获取权限资源数据失败，请刷新页面重新操作。如问题仍旧存在，请联系系统管理员处理。');
					 	}
					 }
					 $.ajax(_p);
					
				},
				
				getIdJson:function(rows){
					var _jsonRows={}
					if(rows){						
						$.each(rows,function(index,data){
							if(data && data.permissionid){
								_jsonRows[data.permissionid] = data	
							}
							
						})	
					}
					return _jsonRows;
				},
				
				/**
				 * 点击角色初始化权限
				 */
				refreshPermissionByClickRole:function(data){
					$.each(data,function(index,row){
						if(row && row.permissionid){							
							var _el = $rolePermissionPermission.treegrid('find',row.permissionid);
							if(_el){
								$rolePermissionPermission.treegrid('select',row.permissionid);
							}
							
						}
					})	
				},
				
				/**
				 * 加载角色初始化权限
				 */
				refreshPermissionByExpandNode:function(data){
					if(currentRows && data){
						
						$.each(data,function(index,row){
							if(row && row.id){
								if(currentRows[row.id]){
									var _el = $rolePermissionPermission.treegrid('find',row.id);
									if(_el){
										$rolePermissionPermission.treegrid('select',row.id);
									}
								}
							}
						})	
						
					}					
				},
				//保存角色权限
				saveRolesPermission:function (e){
					 //删除取消权限
					 if(deletedRows){
					 	var _data = null
						 $.each(deletedRows,function(index,row){
						 	 _data = _data ==null?row.id : _data +',' +row.id;
						 })
						 
						 $.ajax({
							url:baseLeftDelUrl,
							type : 'post',							
							data:{ids:_data},													
							success:function(data){
								msgServ.Msgslide('操作成功');
								if(e && e.currentTarget){
									$(e.currentTarget).linkbutton('enable')
								}
							}
							,
							error:function(){
								msgServ.Msgslide('操作失败');
								if(e && e.currentTarget){
									$(e.currentTarget).linkbutton('enable')
								}
							}
						})		
					 }
					 
					 //新增权限
					 if(insertedRows){
					 	//保存新增权限
					 	 var _data = []
						 $.each(insertedRows,function(index,row){
						 	 _data.push(row);
						 })
						 
						 $.ajax({
							url:baseSaveUrl,
							type : 'post',
							dataType:'json',
							data:$.toJSON(_data),
							contentType:'appliction/json;charset=utf-8',						
							success:function(data){
								msgServ.Msgslide('操作成功');
								if(data){
									private_method.getIdJson(data);
								}
								if(e && e.currentTarget){
									$(e.currentTarget).linkbutton('enable')
								}
							}
							,
							error:function(){
								msgServ.Msgslide('操作失败');
								if(e && e.currentTarget){
									$(e.currentTarget).linkbutton('enable')
								}
							}
							
						})						
					 }else{
						 msgServ.Msgslide('请选择角色并授权');
						 if(e && e.currentTarget){
							$(e.currentTarget).linkbutton('enable')
						}
					 }
					 
				 },
				 
				// 编辑,flag 为form按钮可见性标志
				edit : function(e) {
					var _param = {grid:$rolePermissionRoleGrid,window:$edit_window,href:baseLeftEditUrl,width:600,height:400}
					datagridServ.windowEdit(_param);
					if(e && e.currentTarget){
						$(e.currentTarget).linkbutton('enable')
					}
				},
				// 编辑,flag 为form按钮可见性标志
				add : function(e) {
					$($edit_window).attr('flag','add');					
					$($edit_window).window({href:baseLeftEditUrl,width:600,height:400});
					$($edit_window).window('open')
					
					if(e && e.currentTarget){
						$(e.currentTarget).linkbutton('enable')
					}
				},
				// 删除
				delLeft : function(e) {
					
					datagridServ.delRow({url:baseLeftDelUrl,target:$grid,evt:e});
				},
				//功能按钮监听函数
				function_btn_listenner:function(e){
					
					btnServ.applyButton({buttonEvt:e,buttonConfig:_buttonConfig})
					
				}
			}
			
			
			
			

			var public_method = {
				init:function(doc){
					private_method.init(doc)
				},
				destory:function(){
					currentJobRow = null;
					insertedRows = null;
					deletedRows = null;
				}
			};

			return public_method;

		});